package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author zjx
 * @date 2025-05-17
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */

    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IBedService bedService;
    @Autowired
    private IElderService elderService;
    @Autowired
    private ICheckInConfigService checkInConfigService;
    @Autowired
    private IContractService contractService;


    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        //判断老人是否已入住
        String cardNo = dto.getCheckInElderDto().getIdCardNo();
        Long count = this.lambdaQuery().eq(CheckIn::getIdCardNo, cardNo).eq(CheckIn::getStatus, 0).count();
        if(count>1){
            throw new BaseException("老人已入住");
        }

        //2. 判断符合要求的床位是否可以入住
        Long bedId = dto.getCheckInConfigDto().getBedId();
        Bed bed = bedService.lambdaQuery().eq(Bed::getId, bedId).eq(Bed::getBedStatus, 0).one();
        if(bed==null){
            throw new BaseException("该床位已入住,请更换床位");
        }

        //3. 更新床位状态为已入住
        Bed DB = new Bed();
        DB.setId(bedId);
        DB.setBedNumber(bed.getBedNumber());
        DB.setBedStatus(1);
        DB.setRoomId(dto.getCheckInConfigDto().getRoomId());
        boolean save = bedService.updateById(DB);
        if(!save){
            throw new BaseException("保存床位信息失败");
        }

        //4. 保存老人基本信息
        Elder elder = saveElder(dto, bedId, DB);

        //5. 新增签约信息
        saveContract(dto, elder);

        //6. 新增入住信息
        CheckIn checkIn = saveCheckIn(dto, elder, cardNo, DB);

        //7.新增入住配置
        saveCheckInConfig(dto, checkIn);
    }

    @Override
    public CheckInDetailVo detail(Long id) {
        CheckIn checkIn = this.getById(id);
        if(checkIn==null){
            throw new BaseException("不存在该入住信息");
        }
        CheckInDetailVo vo = new CheckInDetailVo();
        //查询老人信息
        Elder elder = elderService.getById(checkIn.getElderId());
        CheckInElderVo elderVo =new CheckInElderVo();
        BeanUtils.copyProperties(elder, elderVo);
        LocalDate birthday = LocalDate.parse(elder.getBirthday());
        LocalDate now = LocalDate.now();
        int age = Period.between(birthday, now).getYears();
        elderVo.setAge(age);
        vo.setCheckInElderVo(elderVo);

        //查询合同信息
        Contract contract = contractService.lambdaQuery().eq(Contract::getElderId, checkIn.getElderId()).one();
        vo.setContract(contract);

        //查询入住配置信息
        CheckInConfig config = checkInConfigService.lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId()).one();
        CheckInConfigVo checkInConfig = new CheckInConfigVo();
        BeanUtils.copyProperties(config, checkInConfig);
        checkInConfig.setBedNumber(checkIn.getBedNumber());
        checkInConfig.setStartDate(checkIn.getStartDate());
        checkInConfig.setEndDate(checkIn.getEndDate());
        vo.setCheckInConfigVo(checkInConfig);

        //转换家属列表
        String remark = checkIn.getRemark();
        if (StrUtil.isBlank(remark)) {
            vo.setElderFamilyVoList(Collections.emptyList());
        } else if (JSONUtil.isJsonArray(remark)) {
            List<ElderFamilyDto> elderFamilyDto = JSONUtil.toList(remark, ElderFamilyDto.class);
            // 转换逻辑
            List<ElderFamilyVo> elderFamilyVoList = new ArrayList<>();
            elderFamilyDto.forEach(x->{
                ElderFamilyVo familyVo = new ElderFamilyVo();
                BeanUtils.copyProperties(x,familyVo);
                elderFamilyVoList.add(familyVo);
            });
            vo.setElderFamilyVoList(elderFamilyVoList);
        } else {
            throw new BaseException("remark 字段不是合法的 JSON 数组");
        }

        return vo;
    }

    /**
     * 新增入住配置
     * @param dto
     * @param checkIn
     */
    private void saveCheckInConfig(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        boolean result = checkInConfigService.save(checkInConfig);
        if(!result){
            throw new BaseException("保存入住配置信息失败");
        }
    }

    /**
     * 新增入住信息
     * @param dto
     * @param elder
     * @param cardNo
     * @param DB
     * @return
     */
    private @NotNull CheckIn saveCheckIn(CheckInApplyDto dto, Elder elder, String cardNo, Bed DB) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkIn);
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(cardNo);
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(DB.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        boolean checkInResult = this.save(checkIn);
        if(!checkInResult){
            throw new BaseException("保存入住信息");
        }
        return checkIn;
    }

    /**
     * 新增签约信息
     * @param dto
     * @param elder
     */
    private void saveContract(CheckInApplyDto dto, Elder elder) {
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto, contract);
        contract.setElderId(elder.getId());
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        Integer status = LocalDateTime.now().isBefore(contract.getStartDate()) ? 0 : LocalDateTime.now().isBefore(contract.getEndDate()) ? 1 : 2;
        contract.setStatus(status);
        boolean contractResult = contractService.save(contract);
        if(!contractResult){
            throw new BaseException("保存签约信息失败");
        }
    }

    /**
     * 保存老人基本信息
     * @param dto
     * @param bedId
     * @param DB
     * @return
     */
    private @NotNull Elder saveElder(CheckInApplyDto dto, Long bedId, Bed DB) {
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedId(bedId);
        elder.setBedNumber(DB.getBedNumber());
        elder.setStatus(4);
        boolean eld = elderService.save(elder);
        if(!eld){
            throw new BaseException("保存老人基本信息失败");
        }
        return elder;
    }
}
